package com.tools.xxf.updatelib.updateapp;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.tools.xxf.updatelib.R;
import com.tools.xxf.updatelib.utils.SDCardHelper;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;

import static com.tools.xxf.updatelib.utils.ApkUtils.*;

/**
 * TODO:服务下载
 *
 * @author XXF
 *         Create Time : 2017/11/7 15:15
 */
@SuppressWarnings("ALL")
public class UpdateService extends Service {
    public static final String ACTION = "me.shenfan.UPDATE_APP";
    public static final String STATUS = "status";
    public static final String PROGRESS = "progress";
    public static boolean isLoading;

    //下载大小通知频率
    public static final int UPDATE_NUMBER_SIZE = 1;
    public static final int DEFAULT_RES_ID = -1;

    public static final int UPDATE_PROGRESS_STATUS = 0;
    public static final int UPDATE_ERROR_STATUS = -1;
    public static final int UPDATE_SUCCESS_STATUS = 1;

    //params
    private static final String URL = "downloadUrl";
    private static final String ICO_RES_ID = "icoResId";
    private static final String ICO_SMALL_RES_ID = "icoSmallResId";
    private static final String UPDATE_PROGRESS = "updateProgress";
    private static final String STORE_DIR = "storeDir";
    private static final String DOWNLOAD_NOTIFICATION_FLAG = "downloadNotificationFlag";
    private static final String DOWNLOAD_SUCCESS_NOTIFICATION_FLAG =
            "downloadSuccessNotificationFlag";
    private static final String DOWNLOAD_ERROR_NOTIFICATION_FLAG = "downloadErrorNotificationFlag";
    private static final String IS_SEND_BROADCAST = "isSendBroadcast";


    private String downloadUrl;
    private int icoResId;             //default app ico
    private int icoSmallResId;
    private int updateProgress;   //update notification progress when it add number
    private String storeDir;          //default sdcard/Android/package/update
    private int downloadNotificationFlag;
    private int downloadSuccessNotificationFlag;
    private int downloadErrorNotificationFlag;
    private boolean isSendBroadcast;

    private boolean startDownload;//开始下载
    private int lastProgressNumber;
    private NotificationCompat.Builder builder;
    private NotificationManager manager;
    private int notifyId;
    private String appName;
    private LocalBroadcastManager localBroadcastManager;
    private Intent localIntent;
    private DownloadApk downloadApkTask;

    private UpdateProgressListener updateProgressListener;
    private LocalBinder localBinder = new LocalBinder();

    /**
     * Class used for the client Binder.
     */
    public class LocalBinder extends Binder {
        /**
         * set update progress call back
         *
         * @param listener
         */
        public void setUpdateProgressListener(UpdateProgressListener listener) {
            UpdateService.this.setUpdateProgressListener(listener);
        }
    }

    /**
     * a builder class helper use UpdateService
     */
    public static class Builder {

        private String downloadUrl;
        private int icoResId = DEFAULT_RES_ID;             //default app ico
        private int icoSmallResId = DEFAULT_RES_ID;
        private int updateProgress = UPDATE_NUMBER_SIZE;   //update notification progress
        // when it
        // add number
        private String storeDir;          //default sdcard/Android/package/update
        private int downloadNotificationFlag;
        private int downloadSuccessNotificationFlag;
        private int downloadErrorNotificationFlag;
        private boolean isSendBroadcast;

        protected Builder(String downloadUrl) {
            this.downloadUrl = downloadUrl;
        }

        public static Builder create(String downloadUrl) {
            if (downloadUrl == null) {
                throw new NullPointerException("downloadUrl == null");
            }
            return new Builder(downloadUrl);
        }

        public String getDownloadUrl() {
            return downloadUrl;
        }

        public int getIcoResId() {
            return icoResId;
        }

        public Builder setIcoResId(int icoResId) {
            this.icoResId = icoResId;
            return this;
        }

        public int getIcoSmallResId() {
            return icoSmallResId;
        }

        public Builder setIcoSmallResId(int icoSmallResId) {
            this.icoSmallResId = icoSmallResId;
            return this;
        }

        public int getUpdateProgress() {
            return updateProgress;
        }

        public Builder setUpdateProgress(int updateProgress) {
            if (updateProgress < 1) {
                throw new IllegalArgumentException("updateProgress < 1");
            }
            this.updateProgress = updateProgress;
            return this;
        }

        public String getStoreDir() {
            return storeDir;
        }

        public Builder setStoreDir(String storeDir) {
            this.storeDir = storeDir;
            return this;
        }

        public int getDownloadNotificationFlag() {
            return downloadNotificationFlag;
        }

        public Builder setDownloadNotificationFlag(int downloadNotificationFlag) {
            this.downloadNotificationFlag = downloadNotificationFlag;
            return this;
        }

        public int getDownloadSuccessNotificationFlag() {
            return downloadSuccessNotificationFlag;
        }

        public Builder setDownloadSuccessNotificationFlag(int downloadSuccessNotificationFlag) {
            this.downloadSuccessNotificationFlag = downloadSuccessNotificationFlag;
            return this;
        }

        public int getDownloadErrorNotificationFlag() {
            return downloadErrorNotificationFlag;
        }

        public Builder setDownloadErrorNotificationFlag(int downloadErrorNotificationFlag) {
            this.downloadErrorNotificationFlag = downloadErrorNotificationFlag;
            return this;
        }

        public boolean isSendBroadcast() {
            return isSendBroadcast;
        }

        public Builder setIsSendBroadcast(boolean isSendBroadcast) {
            this.isSendBroadcast = isSendBroadcast;
            return this;
        }

        public Builder build(Context context) {
            if (context == null) {
                throw new NullPointerException("context == null");
            }
            Intent intent = new Intent();
            intent.setClass(context, UpdateService.class);
            intent.putExtra(URL, downloadUrl);

            if (icoResId == DEFAULT_RES_ID) {
                icoResId = getIcon(context);
            }

            if (icoSmallResId == DEFAULT_RES_ID) {
                icoSmallResId = icoResId;
            }
            intent.putExtra(ICO_RES_ID, icoResId);
            intent.putExtra(STORE_DIR, storeDir);
            intent.putExtra(ICO_SMALL_RES_ID, icoSmallResId);
            intent.putExtra(UPDATE_PROGRESS, updateProgress);
            intent.putExtra(DOWNLOAD_NOTIFICATION_FLAG, downloadNotificationFlag);
            intent.putExtra(DOWNLOAD_SUCCESS_NOTIFICATION_FLAG,
                    downloadSuccessNotificationFlag);
            intent.putExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, downloadErrorNotificationFlag);
            intent.putExtra(IS_SEND_BROADCAST, isSendBroadcast);
            context.startService(intent);

            return this;
        }

        private int getIcon(Context context) {

            final PackageManager packageManager = context.getPackageManager();
            ApplicationInfo appInfo = null;
            try {
                appInfo = packageManager.getApplicationInfo(context.getPackageName(),
                        PackageManager.GET_META_DATA);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
            if (appInfo != null) {
                return appInfo.icon;
            }
            return 0;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        appName = AppUtils.getAppName();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startLoad(intent, startId);
        LogUtils.d("onStartCommand: ");
        return super.onStartCommand(intent, flags, startId);
    }

    private void startLoad(Intent intent, int startId) {
        if (!startDownload && intent != null) {
            startDownload = true;
            downloadUrl = intent.getStringExtra(URL);
            icoResId = intent.getIntExtra(ICO_RES_ID, DEFAULT_RES_ID);
            icoSmallResId = intent.getIntExtra(ICO_SMALL_RES_ID, DEFAULT_RES_ID);
            storeDir = intent.getStringExtra(STORE_DIR);
            updateProgress = intent.getIntExtra(UPDATE_PROGRESS, UPDATE_NUMBER_SIZE);
            downloadNotificationFlag = intent.getIntExtra(DOWNLOAD_NOTIFICATION_FLAG, 0);
            downloadErrorNotificationFlag = intent.getIntExtra(DOWNLOAD_ERROR_NOTIFICATION_FLAG, 0);
            downloadSuccessNotificationFlag = intent.getIntExtra
                    (DOWNLOAD_SUCCESS_NOTIFICATION_FLAG, 0);
            isSendBroadcast = intent.getBooleanExtra(IS_SEND_BROADCAST, false);

            LogUtils.d("downloadUrl: " + downloadUrl);
            LogUtils.d("icoResId: " + icoResId);
            LogUtils.d("icoSmallResId: " + icoSmallResId);
            LogUtils.d("storeDir: " + storeDir);
            LogUtils.d("updateProgress: " + updateProgress);
            LogUtils.d("downloadNotificationFlag: " + downloadNotificationFlag);
            LogUtils.d("downloadErrorNotificationFlag: " + downloadErrorNotificationFlag);
            LogUtils.d("downloadSuccessNotificationFlag: " + downloadSuccessNotificationFlag);
            LogUtils.d("isSendBroadcast: " + isSendBroadcast);

            notifyId = startId;
            buildNotification();
            buildBroadcast();
            downloadApkTask = new DownloadApk(this);
            downloadApkTask.execute(downloadUrl);
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        startLoad(intent, 0);
        return localBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return true;
    }

    public void setUpdateProgressListener(UpdateProgressListener updateProgressListener) {
        this.updateProgressListener = updateProgressListener;
    }

    private void buildBroadcast() {
        if (!isSendBroadcast) {
            return;
        }
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localIntent = new Intent(ACTION);
    }

    private void sendLocalBroadcast(int status, int progress) {
        if (!isSendBroadcast || localIntent == null) {
            return;
        }
        localIntent.putExtra(STATUS, status);
        localIntent.putExtra(PROGRESS, progress);
        localBroadcastManager.sendBroadcast(localIntent);
    }

    private void buildNotification() {
        manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        sendnotification(0);
    }

    private void sendnotification(int progress) {
        builder = new NotificationCompat.Builder(this);
        builder.setContentTitle(getString(R.string.update_app_model_prepare, appName))
                .setWhen(System.currentTimeMillis())
                .setProgress(100, progress, false)
                .setContentText(getString(R.string.update_app_model_progress, progress, "%"))
                .setSmallIcon(getApplicationInfo().icon)
                .setLargeIcon(BitmapFactory.decodeResource(
                        getResources(), icoResId))
                .setAutoCancel(true)
                .setDefaults(downloadNotificationFlag);
        manager.notify(notifyId, builder.build());
    }

    /**
     * 下载任务开始
     */
    private void start() {
        sendnotification(1);
        sendLocalBroadcast(UPDATE_PROGRESS_STATUS, 1);
        if (updateProgressListener != null) {
            updateProgressListener.start();
        }
    }

    /**
     * @param progress download percent , max 100
     */
    private void update(int progress) {
        if (progress - lastProgressNumber >= updateProgress) {
            lastProgressNumber = progress;
            sendnotification(progress);
            sendLocalBroadcast(UPDATE_PROGRESS_STATUS, progress);
            if (updateProgressListener != null) {
                updateProgressListener.update(progress);
            }
        }
    }

    private class DownloadApk extends AsyncTask<String, Integer, Object> {
        private long oldTime = 0;
        private WeakReference<UpdateService> updateServiceWeakReference;

        DownloadApk(UpdateService service) {
            updateServiceWeakReference = new WeakReference<>(service);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            UpdateService service = updateServiceWeakReference.get();
            if (service != null) {
                service.start();
            }
        }

        @SuppressLint("WorldReadableFiles")
        @Override
        protected Object doInBackground(String... params) {

            final String downloadUrl = params[0];
            LogUtils.d("downloadUrl=" + downloadUrl);
            HttpURLConnection httpConnection = null;
            InputStream is = null;
            FileOutputStream fos = null;
            int updateTotalSize = 0;
            URL url;
            try {
                url = new URL(downloadUrl);
                httpConnection = (HttpURLConnection) url.openConnection();
                httpConnection.setConnectTimeout(20000);

                LogUtils.d("download status code: " + httpConnection.getResponseCode());
                if (httpConnection.getResponseCode() != 200) {
                    //连接异常
                    return new Exception(getResources().getString(R.string.conn_error));
                }

                updateTotalSize = httpConnection.getContentLength();
                String contentType = httpConnection.getHeaderField("Content-Type");

                //apk下载结果返回了文字那么直接返回
                if (contentType.contains("text")) {
                    InputStream stream = httpConnection.getInputStream();
                    byte[] buffer = new byte[(int) updateTotalSize];
                    int read = stream.read(buffer);
                    //TODO 错误文字显示
                    LogUtils.d("error: " + new String(buffer));
                    return new Exception(new String(buffer));
                }
                if (updateTotalSize < 500) {
                    //TODO 文件太小认定不是apk
                    LogUtils.d("error: 文件太小认定不是apk");
                    return new Exception(getResources().getString(R.string.load_fail));
                }
                File downloadDir = getDownloadDir(updateServiceWeakReference
                        .get(), storeDir, updateTotalSize);
                if (downloadDir == null) {
                    return new Exception(getResources().getString(R.string.creatFile_error));
                }
                String fileName = getSaveFileName(downloadUrl);
                final File file = new File(downloadDir, fileName);
                LogUtils.d("download url is " + downloadUrl);
                LogUtils.d("download apk cache at " + file.getAbsolutePath());
                File dir = file.getParentFile();
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                if (file.exists()) {
                    if (updateTotalSize == file.length()) {
                        // 下载完成
                        return file;
                    } else {
                        file.delete();
                    }
                }
                isLoading = true;
                boolean newFile = file.createNewFile();
                if (file.getAbsolutePath().contains("data/data") || file.getAbsolutePath()
                        .contains("data/user/0")) {
                    //获取一个写入文件流对象
                    fos = openFileOutput(fileName, Context.MODE_WORLD_READABLE);
                } else {
                    fos = new FileOutputStream(file);
                }
                is = httpConnection.getInputStream();
                byte buffer[] = new byte[1024];

                int readSize = 0;
                int currentSize = 0;

                while ((readSize = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, readSize);
                    currentSize += readSize;
                    publishProgress((currentSize * 100 / updateTotalSize));
                }
                return file;

            } catch (Exception e) {
                e.printStackTrace();
                return e;
            } finally {
                if (httpConnection != null) {
                    httpConnection.disconnect();
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fos != null) {
                    try {
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            long newTime = System.currentTimeMillis();
            if (newTime - oldTime > 500) {//500ms更新一次通知,防止网上过快频繁,导致通知阻塞
                oldTime = newTime;
                LogUtils.d("current progress is " + values[0]);
                UpdateService service = updateServiceWeakReference.get();
                if (service != null) {
                    service.update(values[0]);
                }
            }
        }

        @Override
        protected void onPostExecute(Object s) {
            super.onPostExecute(s);
            UpdateService service = updateServiceWeakReference.get();
            isLoading = false;
            LogUtils.d("onPostExecute");
            if (service != null && s != null) {
                if (s instanceof File)
                    service.success((File) s);
                if (s instanceof Exception) {
                    service.error((Exception) s);
                }
            }
        }
    }

    private void success(File file) {
        builder.setProgress(0, 0, false);
        builder.setContentText(getString(R.string.update_app_model_success));
        Intent i = installIntent(this, file.getAbsolutePath());
        PendingIntent intent = PendingIntent.getActivity(this, 0, i, PendingIntent
                .FLAG_UPDATE_CURRENT);
        builder.setContentIntent(intent);
        builder.setDefaults(downloadSuccessNotificationFlag);
        Notification n = builder.build();
        n.contentIntent = intent;
        manager.notify(notifyId, n);
        sendLocalBroadcast(UPDATE_SUCCESS_STATUS, 100);
        if (updateProgressListener != null) {
            updateProgressListener.success();
        }
        startActivity(i);
        stopSelf();
    }

    private void error(Exception e) {
        LogUtils.d("" + e.getMessage());
        Intent i = webLauncher(downloadUrl);
        PendingIntent intent = PendingIntent.getActivity(this, 0, i,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentText(getString(R.string.update_app_model_error));
        builder.setContentIntent(intent);
        builder.setProgress(0, 0, false);
        builder.setDefaults(downloadErrorNotificationFlag);
        Notification n = builder.build();
        n.contentIntent = intent;
        manager.notify(notifyId, n);
        sendLocalBroadcast(UPDATE_ERROR_STATUS, -1);
        if (updateProgressListener != null) {
            updateProgressListener.error(e);
        }
        Toast.makeText(UpdateService.this, e.getMessage(), Toast.LENGTH_LONG).show();

        stopSelf();
    }

    @Override
    public void onDestroy() {
        LogUtils.d("销毁服务");
        if (downloadApkTask != null) {
            downloadApkTask.cancel(true);
        }

        if (updateProgressListener != null) {
            updateProgressListener = null;
        }
        localIntent = null;
        builder = null;
        isLoading = false;
        super.onDestroy();
    }

}
